package org.mat.ipaas.ucenter.service.modules.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.mat.ipaas.ucenter.service.api.system.SysAnnouncementSendRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysAnnouncementSendDTO;
import org.mat.ipaas.ucenter.service.dto.system.model.AnnouncementSendModelDTO;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.util.SessionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.constant.DataBaseConstant;
import org.mat.ipaas.ucenter.biz.common.constant.WebsocketConst;
import org.mat.ipaas.ucenter.biz.common.util.SqlInjectionUtil;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.modules.message.websocket.WebSocket;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysAnnouncementSend;
import org.mat.ipaas.ucenter.biz.modules.system.model.AnnouncementSendModel;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysAnnouncementSendService;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

/**
 * @Title: Controller
 * 用户通告阅读标记表
 */
@RestController
@RequestMapping("/sys/sysAnnouncementSend")
@Slf4j
public class SysAnnouncementSendController implements SysAnnouncementSendRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysAnnouncementSendService sysAnnouncementSendService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 分页列表查询
     *
     * @param sysAnnouncementSendDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public MatApiResponse<IPage<SysAnnouncementSendDTO>> queryPageList(SysAnnouncementSendDTO sysAnnouncementSendDTO,
                                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                       HttpServletRequest req) {
        MatApiResponse<IPage<SysAnnouncementSendDTO>> matApiResponse = new MatApiResponse<>();
        SysAnnouncementSend sysAnnouncementSend = toSysAnnouncementSend(sysAnnouncementSendDTO);
        QueryWrapper<SysAnnouncementSend> queryWrapper = new QueryWrapper<SysAnnouncementSend>(sysAnnouncementSend);
        Page<SysAnnouncementSend> page = new Page<SysAnnouncementSend>(pageNo, pageSize);
        //排序逻辑 处理
        String column = req.getParameter("column");
        String order = req.getParameter("order");

        //issues/3331 SQL injection vulnerability
        SqlInjectionUtil.filterContent(column);
        SqlInjectionUtil.filterContent(order);

        if (oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) {
            if (DataBaseConstant.SQL_ASC.equals(order)) {
                queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column));
            } else {
                queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column));
            }
        }
        IPage<SysAnnouncementSend> pageList = sysAnnouncementSendService.page(page, queryWrapper);
        //log.info("查询当前页："+pageList.getCurrent());
        //log.info("查询当前页数量："+pageList.getSize());
        //log.info("查询结果数量："+pageList.getRecords().size());
        //log.info("数据总数："+pageList.getTotal());
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysAnnouncementSendDTOPage(pageList));
        return matApiResponse;
    }


    /**
     * 添加
     *
     * @param sysAnnouncementSendDTO
     * @return
     */
    @PostMapping(value = "/add")
    public MatApiResponse<SysAnnouncementSendDTO> add(@RequestBody SysAnnouncementSendDTO sysAnnouncementSendDTO) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        try {
            sysAnnouncementSendService.save(toSysAnnouncementSend(sysAnnouncementSendDTO));
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param sysAnnouncementSendDTO
     * @return
     */
    @PutMapping(value = "/edit")
    public MatApiResponse<SysAnnouncementSendDTO> eidt(@RequestBody SysAnnouncementSendDTO sysAnnouncementSendDTO) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        SysAnnouncementSend sysAnnouncementSendEntity = sysAnnouncementSendService.getById(sysAnnouncementSendDTO.getId());
        if (sysAnnouncementSendEntity == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysAnnouncementSendService.updateById(toSysAnnouncementSend(sysAnnouncementSendDTO));
            //TODO 返回false说明什么？
            if (ok) {
                matApiResponse.success("操作成功!");
            }
        }

        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public MatApiResponse<SysAnnouncementSendDTO> delete(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
        if (sysAnnouncementSend == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysAnnouncementSendService.removeById(id);
            if (ok) {
                matApiResponse.success("删除成功!");
            }
        }

        return matApiResponse;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<SysAnnouncementSendDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        if (ids == null || "".equals(ids.trim())) {
            matApiResponse.fail("参数不识别！");
        } else {
            this.sysAnnouncementSendService.removeByIds(Arrays.asList(ids.split(",")));
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public MatApiResponse<SysAnnouncementSendDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
        if (sysAnnouncementSend == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysAnnouncementSendDTO(sysAnnouncementSend));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * @param json
     * @return
     * @功能：更新用户系统消息阅读状态
     */
    @PutMapping(value = "/editByAnntIdAndUserId")
    public MatApiResponse<SysAnnouncementSendDTO> editById(@RequestBody JSONObject json) {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        String anntId = json.getString("anntId");
        LoginUserDTO sysUser = sessionService.getLoginUser();
        String userId = sysUser.getId();
        LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
        updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
        updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
        updateWrapper.last("where annt_id ='" + anntId + "' and user_id ='" + userId + "'");
        SysAnnouncementSend announcementSend = new SysAnnouncementSend();
        sysAnnouncementSendService.update(announcementSend, updateWrapper);
        matApiResponse.setSuccess(true);
        return matApiResponse;
    }

    /**
     * @return
     * @功能：获取我的消息
     */
    @GetMapping(value = "/getMyAnnouncementSend")
    public MatApiResponse<Page<AnnouncementSendModelDTO>> getMyAnnouncementSend(@SpringQueryMap AnnouncementSendModelDTO announcementSendModelDTO,
                                                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        MatApiResponse<Page<AnnouncementSendModelDTO>> matApiResponse = new MatApiResponse<>();

        LoginUserDTO sysUser = sessionService.getLoginUser();
        String userId = sysUser.getId();
        AnnouncementSendModel announcementSendModel = toAnnouncementSendModel(announcementSendModelDTO);
        announcementSendModel.setUserId(userId);
        announcementSendModel.setPageNo((pageNo - 1) * pageSize);
        announcementSendModel.setPageSize(pageSize);
        Page<AnnouncementSendModel> pageList = new Page<AnnouncementSendModel>(pageNo, pageSize);
        pageList = sysAnnouncementSendService.getMyAnnouncementSendPage(pageList, announcementSendModel);
        matApiResponse.setData(toAnnouncementSendModelPage(pageList));
        matApiResponse.setSuccess(true);
        return matApiResponse;
    }



    /**
     * @return
     * @功能：一键已读
     */
    @PutMapping(value = "/readAll")
    public MatApiResponse<SysAnnouncementSendDTO> readAll() {
        MatApiResponse<SysAnnouncementSendDTO> matApiResponse = new MatApiResponse<>();
        LoginUserDTO sysUser = sessionService.getLoginUser();
        String userId = sysUser.getId();
        LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
        updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
        updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
        updateWrapper.last("where user_id ='" + userId + "'");
        SysAnnouncementSend announcementSend = new SysAnnouncementSend();
        sysAnnouncementSendService.update(announcementSend, updateWrapper);
        JSONObject socketParams = new JSONObject();
        socketParams.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
        webSocket.sendMessage(socketParams.toJSONString());
        matApiResponse.setSuccess(true);
        matApiResponse.setMessage("全部已读");
        return matApiResponse;
    }


    /**
     * 根据消息发送记录ID获取消息内容
     *
     * @param sendId
     * @return
     */
    @GetMapping(value = "/getOne")
    public MatApiResponse<AnnouncementSendModelDTO> getOne(@RequestParam(name = "sendId", required = true) String sendId) {
        AnnouncementSendModel model = sysAnnouncementSendService.getOne(sendId);
        return MatApiResponse.success(toAnnouncementSendModelDTO(model));
    }



    private Page<SysAnnouncementSendDTO> toSysAnnouncementSendDTOPage(IPage<SysAnnouncementSend> pageList) {
        Page<SysAnnouncementSendDTO> sysAnnouncementSendDTOPage = new Page<>();
        List<SysAnnouncementSendDTO> sysAnnouncementSendDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysAnnouncementSend sysAnnouncementSend : pageList.getRecords()) {
                sysAnnouncementSendDTOList.add(toSysAnnouncementSendDTO(sysAnnouncementSend));
            }
        }

        sysAnnouncementSendDTOPage.setTotal(pageList.getTotal());
        sysAnnouncementSendDTOPage.setSize(pageList.getSize());
        sysAnnouncementSendDTOPage.setCurrent(pageList.getCurrent());
        sysAnnouncementSendDTOPage.setRecords(sysAnnouncementSendDTOList);
        return sysAnnouncementSendDTOPage;
    }

    private SysAnnouncementSendDTO toSysAnnouncementSendDTO(SysAnnouncementSend sysAnnouncementSend) {
        if (sysAnnouncementSend == null) {
            return null;
        }
        SysAnnouncementSendDTO sysAnnouncementSendDTO = new SysAnnouncementSendDTO();
        sysAnnouncementSendDTO.setId(sysAnnouncementSend.getId());
        sysAnnouncementSendDTO.setAnntId(sysAnnouncementSend.getAnntId());
        sysAnnouncementSendDTO.setUserId(sysAnnouncementSend.getUserId());
        sysAnnouncementSendDTO.setReadFlag(sysAnnouncementSend.getReadFlag());
        sysAnnouncementSendDTO.setReadTime(sysAnnouncementSend.getReadTime());
        sysAnnouncementSendDTO.setCreateBy(sysAnnouncementSend.getCreateBy());
        sysAnnouncementSendDTO.setCreateTime(sysAnnouncementSend.getCreateTime());
        sysAnnouncementSendDTO.setUpdateBy(sysAnnouncementSend.getUpdateBy());
        sysAnnouncementSendDTO.setUpdateTime(sysAnnouncementSend.getUpdateTime());
        sysAnnouncementSendDTO.setStarFlag(sysAnnouncementSend.getStarFlag());
        return sysAnnouncementSendDTO;
    }

    private SysAnnouncementSend toSysAnnouncementSend(SysAnnouncementSendDTO sysAnnouncementSendDTO) {
        if (sysAnnouncementSendDTO == null) {
            return null;
        }
        SysAnnouncementSend sysAnnouncementSend = new SysAnnouncementSend();
        sysAnnouncementSend.setId(sysAnnouncementSendDTO.getId());
        sysAnnouncementSend.setAnntId(sysAnnouncementSendDTO.getAnntId());
        sysAnnouncementSend.setUserId(sysAnnouncementSendDTO.getUserId());
        sysAnnouncementSend.setReadFlag(sysAnnouncementSendDTO.getReadFlag());
        sysAnnouncementSend.setReadTime(sysAnnouncementSendDTO.getReadTime());
        sysAnnouncementSend.setCreateBy(sysAnnouncementSendDTO.getCreateBy());
        sysAnnouncementSend.setCreateTime(sysAnnouncementSendDTO.getCreateTime());
        sysAnnouncementSend.setUpdateBy(sysAnnouncementSendDTO.getUpdateBy());
        sysAnnouncementSend.setUpdateTime(sysAnnouncementSendDTO.getUpdateTime());
        sysAnnouncementSend.setStarFlag(sysAnnouncementSendDTO.getStarFlag());
        return sysAnnouncementSend;
    }


    private Page<AnnouncementSendModelDTO> toAnnouncementSendModelPage(Page<AnnouncementSendModel> pageList) {
        Page<AnnouncementSendModelDTO> announcementSendModelDTOPage = new Page<>();
        List<AnnouncementSendModelDTO> announcementSendModelDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())){
            for (AnnouncementSendModel announcementSendModel : pageList.getRecords()) {
                announcementSendModelDTOList.add(toAnnouncementSendModelDTO(announcementSendModel));
            }
        }

        announcementSendModelDTOPage.setTotal(pageList.getTotal());
        announcementSendModelDTOPage.setSize(pageList.getSize());
        announcementSendModelDTOPage.setCurrent(pageList.getCurrent());
        announcementSendModelDTOPage.setRecords(announcementSendModelDTOList);
        return announcementSendModelDTOPage;
    }

    private AnnouncementSendModelDTO toAnnouncementSendModelDTO(AnnouncementSendModel announcementSendModel) {
        if (announcementSendModel == null) {
            return null;
        }
        AnnouncementSendModelDTO announcementSendModelDTO = new AnnouncementSendModelDTO();
        announcementSendModelDTO.setId(announcementSendModel.getId());
        announcementSendModelDTO.setAnntId(announcementSendModel.getAnntId());
        announcementSendModelDTO.setUserId(announcementSendModel.getUserId());
        announcementSendModelDTO.setTitile(announcementSendModel.getTitile());
        announcementSendModelDTO.setMsgContent(announcementSendModel.getMsgContent());
        announcementSendModelDTO.setSender(announcementSendModel.getSender());
        announcementSendModelDTO.setPriority(announcementSendModel.getPriority());
        announcementSendModelDTO.setReadFlag(announcementSendModel.getReadFlag());
        announcementSendModelDTO.setSendTime(announcementSendModel.getSendTime());
        announcementSendModelDTO.setPageNo(announcementSendModel.getPageNo());
        announcementSendModelDTO.setPageSize(announcementSendModel.getPageSize());
        announcementSendModelDTO.setMsgCategory(announcementSendModel.getMsgCategory());
        announcementSendModelDTO.setBusId(announcementSendModel.getBusId());
        announcementSendModelDTO.setBusType(announcementSendModel.getBusType());
        announcementSendModelDTO.setOpenType(announcementSendModel.getOpenType());
        announcementSendModelDTO.setOpenPage(announcementSendModel.getOpenPage());
        announcementSendModelDTO.setBizSource(announcementSendModel.getBizSource());
        announcementSendModelDTO.setMsgAbstract(announcementSendModel.getMsgAbstract());
        return announcementSendModelDTO;
    }

    private AnnouncementSendModel toAnnouncementSendModel(AnnouncementSendModelDTO announcementSendModelDTO) {
        if (announcementSendModelDTO == null) {
            return null;
        }
        AnnouncementSendModel announcementSendModel = new AnnouncementSendModel();
        announcementSendModel.setId(announcementSendModelDTO.getId());
        announcementSendModel.setAnntId(announcementSendModelDTO.getAnntId());
        announcementSendModel.setUserId(announcementSendModelDTO.getUserId());
        announcementSendModel.setTitile(announcementSendModelDTO.getTitile());
        announcementSendModel.setMsgContent(announcementSendModelDTO.getMsgContent());
        announcementSendModel.setSender(announcementSendModelDTO.getSender());
        announcementSendModel.setPriority(announcementSendModelDTO.getPriority());
        announcementSendModel.setReadFlag(announcementSendModelDTO.getReadFlag());
        announcementSendModel.setSendTime(announcementSendModelDTO.getSendTime());
        announcementSendModel.setPageNo(announcementSendModelDTO.getPageNo());
        announcementSendModel.setPageSize(announcementSendModelDTO.getPageSize());
        announcementSendModel.setMsgCategory(announcementSendModelDTO.getMsgCategory());
        announcementSendModel.setBusId(announcementSendModelDTO.getBusId());
        announcementSendModel.setBusType(announcementSendModelDTO.getBusType());
        announcementSendModel.setOpenType(announcementSendModelDTO.getOpenType());
        announcementSendModel.setOpenPage(announcementSendModelDTO.getOpenPage());
        announcementSendModel.setBizSource(announcementSendModelDTO.getBizSource());
        announcementSendModel.setMsgAbstract(announcementSendModelDTO.getMsgAbstract());
        return announcementSendModel;
    }

}
